package com.example.xjt.biz;

import com.example.xjt.orm.user.UserDO;
import com.example.xjt.orm.user.UserRepo;
import com.example.xjt.restful.APIException;
import com.example.xjt.restful.ResultCodeEnum;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserService {
    @Autowired
    private UserRepo userRepo;

    /**
     * caffeineCache技术--内存缓存技术
     * https://zhuanlan.zhihu.com/p/109226599
     * https://www.cnblogs.com/woshimrf/p/springboot-cache.html
     * https://www.jianshu.com/p/2e2e9b6b1853
     * @param id
     * @return
     */

    @Cacheable(cacheNames = "user", key = "#id")
    public UserDO getById(Long id) {
        return userRepo.findById(id).orElse(null);
    }

    @CacheEvict(cacheNames = "user", key = "#id")
    public void delUser(Long id) {
        UserDO userDO = userRepo.findById(id).orElse(null);
        if (userDO != null) {
            userRepo.delete(userDO);
        }
    }

    @CachePut(cacheNames = "user", key = "#userInfo.id")
    public UserDO addUser(UserDO userInfo) {
        return userRepo.save(userInfo);
    }

    @CachePut(cacheNames = "user", key = "#userInfo.id")
    public UserDO updateUserInfo(UserDO userInfo) {
        UserDO userDO = userRepo.findById(userInfo.getId()).orElse(null);
        if (userDO != null) {
            BeanUtils.copyProperties(userInfo,userDO);
            userRepo.save(userDO);
        }
        return userDO;
    }


    public Integer judgeMoreThan999(int a, int b) {
        int r = a + b;
        if (r < 0) {
            throw new APIException();
        }
        if (r < 999 && r > 0) {
            //适用于 有某业务异常，不往下执行后续业务，直接抛出
            throw new APIException(ResultCodeEnum.BIZ_ERROR);
        } else {
            return r;
        }
    }


    @Transactional(rollbackFor = Exception.class)
    public void test() {
        System.err.println(userRepo.updateRemark(1L, "wer3"));
    }


    @Transactional(rollbackFor = Exception.class)
    public void testError() {
        userRepo.updateRemark(1L, "wer3");
        int a = 3 / 0; //测试除0异常会不会引起事务 , 实测不管 本语句在 updateRemark之前或之后，均会引起事务回退
    }
}
